/* Tools
 * General purpose functions to auxiliate on operations not implemented by standard libs
 *
 * Last Modified: 30.11.2013
 * Author: Guilherme S.G.
 */

#ifndef __JB_TOOLS_H__
#define __JB_TOOLS_H__

#include <vector>
#include <string>
#include <sstream>
#include <opencv2/opencv.hpp>

namespace tools
{
    inline std::vector<std::string> &split_aux(const std::string &s_, char delim_, std::vector<std::string> &elems_)
    {
        std::stringstream ss(s_);
        std::string item;
        
        while(std::getline(ss, item, delim_))
            elems_.push_back(item);
        
        return elems_;
    }
    
    inline std::vector<std::string> split(const std::string &s_, char delim_)
    {
        std::vector<std::string> elems;
        split_aux(s_, delim_, elems);
        return elems;
    }
    
    inline bool detectRectangle(cv::Mat *m_, int startI_, int startJ_, int *endI_, int *endJ_)
    {
        int zeroCount = 0, oneCount = 0;
        *endI_ = *endJ_ = 0;
        
        for(int j = startJ_; j < m_->cols; j++)
        {
            if(m_->at<uchar>(startI_, j) > 0)
            {
                oneCount++;
            }
            else
            {
                if(++zeroCount == 10)
                {
                    if(oneCount >= 10) //Big enough - width acquired
                    {
                        *endJ_ = j-zeroCount;
                        oneCount = 0;
                        zeroCount = 0;
                    }
                    else //Not big enough
                        return false;
                }
            }
        }
        
        // In case the hands are going off the screen (no black pixels at the right)
        if(oneCount >= 10)
        {
            *endJ_ = m_->cols-zeroCount;
            oneCount = 0;
            zeroCount = 0;
        }
        
        for(int i = startI_; i < m_->rows; i++)
        {
            if(m_->at<uchar>(i, startJ_) > 0)
            {
                oneCount++;
            }
            else
            {
                if(++zeroCount == 10)
                {
                    zeroCount = 0;
                    
                    if(oneCount >= 10) //Big enough - height acquired
                    {
                        *endI_ = i-zeroCount;
                    }
                    else //Not big enough
                        return false;
                }
            }
        }
        
        // In case the hands are going off the screen (no black pixels at the bottom)
        if(oneCount >= 10)
        {
            *endI_ = m_->rows-zeroCount;
            oneCount = 0;
            zeroCount = 0;
        }
        
        return true;
    }
}

#endif
